<template>
  <uni-nav-bar
    :border="false"
    left-icon="back"
    @clickLeft="goBack"
    fixed
    title="查看二维码"
    background-color="#fa8f20"
    color="white"
  />
  <view class="container">
    <!-- 二维码卡片 -->
    <view class="qr-card">
      <!-- 店铺名称 -->
      <view class="store-name">
        <uni-icons type="shop" size="20" color="#333"></uni-icons>
        <text class="name-text">{{
          qrCodeData.merchantName || "暂无商户名称"
        }}</text>
      </view>

      <!-- 二维码区域 -->
      <view class="qr-wrapper">
        <!-- 二维码图片 -->
        <view class="qr-container">
          <!-- 加载中 -->
          <view v-if="qrCodeLoading" class="qr-loading">
            <uni-load-more status="loading" />
          </view>
          <!-- 二维码图片 -->
          <image
            v-else-if="qrCodeData.qrcodeLink"
            :src="qrCodeData.qrcodeLink"
            class="qr-image"
            mode="aspectFit"
          ></image>
          <!-- 空状态 -->
          <view v-else class="qr-empty">
            <text class="empty-text">暂无收款码</text>
          </view>
        </view>
      </view>

      <!-- 积分比例 -->
      <view class="points-ratio">
        <text class="ratio-label">当前让利比例</text>
        <text class="ratio-value"
          >{{ Math.round((qrCodeData.offerDiscountsRatio || 0) * 100) }}%</text
        >
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-buttons">
      <view class="action-btn manage-btn" @click="handleModifyRatio">
        <uni-icons type="compose" size="20"></uni-icons>
        <text>修改当前比例</text>
      </view>

      <view class="action-btn save-btn" @click="handleSaveImage">
        <uni-icons type="download" size="20"></uni-icons>
        <text>保存图片</text>
      </view>
    </view>

    <!-- 积分比例选择器 -->
    <uni-popup ref="ratioPickerRef" type="bottom">
      <view class="ratio-picker-modal">
        <view class="picker-header">
          <text
            class="picker-cancel"
            :class="{ disabled: updateLoading }"
            @click="closeRatioPicker"
            >取消</text
          >
          <text class="picker-title">积分比例</text>
          <text
            class="picker-confirm"
            :class="{ disabled: updateLoading }"
            @click="confirmRatio"
          >
            {{ updateLoading ? "保存中..." : "确定" }}
          </text>
        </view>

        <picker-view
          class="picker-view"
          :value="pickerValue"
          @change="pickerChange"
          :indicator-style="indicatorStyle"
          :disabled="updateLoading"
        >
          <picker-view-column>
            <view
              v-for="(ratio, index) in ratioOptions"
              :key="index"
              class="picker-item"
            >
              {{ ratio }}%
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRequest } from "ahooks-vue";
import { useStoreStore } from "@/store/modules/store";
import { useUserStore } from "@/store/modules/user";
import { getStoreManagement, getQrCode } from "@/api/mine";

// 使用 Pinia store
const storeStore = useStoreStore();
const userStore = useUserStore();

const goBack = () => {
  uni.navigateBack();
};

// 获取收款码接口
const { loading: qrCodeLoading, run: fetchQrCode } = useRequest(
  () =>
    getQrCode({
      merchantId: storeStore.storeId,
      userId: userStore.userInfo?.userId,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取收款码成功：", response);
      if (response?.data) {
        // qrCodeData.value = {
        //   storeName: response.data.storeName || storeStore.merchantName || "",
        //   qrCodeUrl: response.data.qrCodeUrl || "",
        //   pointsRatio: response.data.pointsRatio || 0,
        // };
        qrCodeData.value = response.data;
      }
    },
    onError: (error) => {
      console.error("获取收款码失败：", error);
      uni.showToast({
        title: "获取收款码失败",
        icon: "none",
      });
    },
  }
);

// 二维码数据（单个）
const qrCodeData = ref({
  merchantName: "",
  qrcodeLink: "",
  offerDiscountsRatio: 0,
});

// 比例选择器相关
const ratioPickerRef = ref(null);
const ratioOptions = ref([]); // 3% 到 20% 的所有整数比例
const pickerValue = ref([0]);
const selectedRatioValue = ref(3);
const indicatorStyle = "height: 50px;";

// 初始化比例选项（3% - 20%）
const initRatioOptions = () => {
  const options = [];
  for (let i = 3; i <= 20; i++) {
    options.push(i);
  }
  ratioOptions.value = options;
};

// 修改当前比例
const handleModifyRatio = () => {
  if (ratioOptions.value.length === 0) {
    initRatioOptions();
  }
  // 将后端返回的小数转换为百分比整数（0.03 -> 3）
  const currentRatioPercent = Math.round(
    (qrCodeData.value.offerDiscountsRatio || 0) * 100
  );
  // 找到当前比例在选项中的索引
  const currentIndex = ratioOptions.value.indexOf(currentRatioPercent);
  pickerValue.value = [currentIndex >= 0 ? currentIndex : 0];
  selectedRatioValue.value =
    currentIndex >= 0
      ? ratioOptions.value[currentIndex]
      : ratioOptions.value[0];
  ratioPickerRef.value?.open();
};

// 关闭比例选择器
const closeRatioPicker = () => {
  ratioPickerRef.value?.close();
};

// picker值改变
const pickerChange = (e) => {
  const index = e.detail.value[0];
  selectedRatioValue.value = ratioOptions.value[index];
  pickerValue.value = [index];
};

// 修改积分比例接口
const { loading: updateLoading, run: updateRatio } = useRequest(
  (ratio) =>
    getStoreManagement({
      merchantId: storeStore.storeId,
      offerDiscountsRatio: ratio,
      userId: userStore.userInfo?.userId,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("修改积分比例成功：", response);
      closeRatioPicker();
      uni.showToast({
        title: "修改成功",
        icon: "none",
      });
      // 修改成功后重新获取收款码
      fetchQrCode();
    },
    onError: (error) => {
      console.error("修改积分比例失败：", error);
      closeRatioPicker();
      uni.showToast({
        title: "修改失败，请重试",
        icon: "none",
      });
    },
  }
);

// 确认选择比例
const confirmRatio = () => {
  // 检查必要参数
  if (!storeStore.storeId || !userStore.userInfo?.userId) {
    uni.showToast({
      title: "缺少必要参数",
      icon: "none",
    });
    return;
  }

  // 将后端返回的小数转换为百分比整数进行比较（0.03 -> 3）
  const currentRatioPercent = Math.round(
    (qrCodeData.value.offerDiscountsRatio || 0) * 100
  );

  // 如果比例没有变化，直接关闭
  if (selectedRatioValue.value === currentRatioPercent) {
    closeRatioPicker();
    return;
  }

  // 将百分比整数转换为小数传给后端（3 -> 0.03）
  const ratioDecimal = selectedRatioValue.value / 100;
  // 调用接口更新比例
  updateRatio(ratioDecimal);
};

// 保存图片
const handleSaveImage = () => {
  if (!qrCodeData.value.qrcodeLink) {
    uni.showToast({
      title: "暂无收款码",
      icon: "none",
    });
    return;
  }

  // #ifdef H5
  // H5 环境下直接下载图片
  const link = document.createElement("a");
  link.href = qrCodeData.value.qrcodeLink;
  link.download = `收款码_${Date.now()}.png`;
  link.target = "_blank";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  uni.showToast({
    title: "开始下载",
    icon: "none",
  });
  // #endif

  // #ifndef H5
  // 小程序/App 环境下使用 uni.downloadFile
  uni.showLoading({
    title: "保存中...",
  });

  uni.downloadFile({
    url: qrCodeData.value.qrcodeLink,
    success: (res) => {
      if (res.statusCode === 200) {
        // 保存图片到相册
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            uni.hideLoading();
            uni.showToast({
              title: "保存成功",
              icon: "none",
            });
          },
          fail: (err) => {
            uni.hideLoading();
            // 可能是权限问题
            if (err.errMsg.includes("auth")) {
              uni.showModal({
                title: "提示",
                content: "请授权保存图片到相册",
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    uni.openSetting();
                  }
                },
              });
            } else {
              uni.showToast({
                title: "保存失败",
                icon: "none",
              });
            }
          },
        });
      } else {
        uni.hideLoading();
        uni.showToast({
          title: "下载失败",
          icon: "none",
        });
      }
    },
    fail: () => {
      uni.hideLoading();
      uni.showToast({
        title: "下载失败",
        icon: "none",
      });
    },
  });
  // #endif
};

// 页面挂载时初始化
onMounted(() => {
  // 初始化比例选项
  initRatioOptions();

  // 从本地缓存恢复店铺和用户信息
  storeStore.hydrateFromStorage();
  userStore.hydrateFromStorage();

  console.log("店铺信息：", {
    merchantId: storeStore.storeId,
    merchantName: storeStore.merchantName,
  });
  console.log("用户信息：", userStore.userInfo);

  // 获取收款码数据
  if (storeStore.storeId && userStore.userInfo?.userId) {
    fetchQrCode();
  } else {
    console.warn("缺少 merchantId 或 userId，无法获取收款码");
  }
});
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #fa8f20;
  padding: 20rpx;
}

.qr-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
}

.store-name {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding-bottom: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.name-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.qr-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
}

.qr-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
}

.qr-image {
  width: 400rpx;
  height: 400rpx;
  border: 2rpx solid #f5f5f5;
  border-radius: 8rpx;
}

.qr-loading {
  width: 400rpx;
  height: 400rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-empty {
  width: 400rpx;
  height: 400rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 8rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.points-ratio {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding-top: 32rpx;
  border-top: 1rpx solid #f5f5f5;
}

.ratio-label {
  font-size: 28rpx;
  color: #666;
  flex: 1;
}

.ratio-value {
  font-size: 36rpx;
  font-weight: bold;
}

.bottom-buttons {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  height: 88rpx;
  background: #fff;
  border-radius: 12rpx;
  font-size: 32rpx;

  border: 2rpx solid #ff6700;
  transition: all 0.3s;

  &:active {
    background: #fff5f0;
  }

  text {
    font-weight: 500;
  }
}

// 比例选择器
.ratio-picker-modal {
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.picker-cancel {
  font-size: 28rpx;
  color: #666;

  &:active {
    opacity: 0.6;
  }

  &.disabled {
    opacity: 0.4;
    pointer-events: none;
  }
}

.picker-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.picker-confirm {
  font-size: 28rpx;
  color: #ff9500;

  &:active {
    opacity: 0.6;
  }

  &.disabled {
    opacity: 0.4;
    pointer-events: none;
  }
}

.picker-view {
  height: 400rpx;
  padding: 0 32rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  line-height: 50px;
  font-size: 32rpx;
  color: #333;
}
</style>
